package com.xinlianshiye.im.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;

@Slf4j
@Component
public class AuthUtil {

    public static final String issuer = "im";

    public String genAccessToken(String id, String secret) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTCreator.Builder builder = JWT.create().withIssuer(issuer);
        builder.withClaim("id", id);
        return builder.sign(algorithm);
    }

    public String verifyAccessToken(String accessToken, String secret) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build();
        DecodedJWT jwt = verifier.verify(accessToken);
        Map<String, Claim> map = jwt.getClaims();
        return map.get("id").asString();
    }
}
